package cn.kdyzm.twofa.controller.web;

import cn.kdyzm.twofa.entity.SysUser;
import cn.kdyzm.twofa.entity.SysUser2fa;
import cn.kdyzm.twofa.mapper.ISysUserMapper;
import cn.kdyzm.twofa.service.ISysUser2faService;
import cn.kdyzm.twofa.service.ITwoFaService;
import com.google.zxing.WriterException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author kdyzm
 * @date 2025/6/13
 */
@Controller
@RequestMapping
@Slf4j
@AllArgsConstructor
public class TwoFaController {

    private final ISysUserMapper sysUserMapper;

    private final ITwoFaService twoFaService;

    private final ISysUser2faService sysUser2faService;

    @GetMapping("/2fa_overview")
    public String twofaOverview(Model model, @CookieValue("userId") Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        model.addAttribute("user", sysUser);
        return "2fa_overview_view";
    }

    @GetMapping("/2fa")
    public String twofa(Model model, @CookieValue("userId") Long userId) throws IOException, WriterException {
        log.info("进入两步验证页面");
        SysUser sysUser = sysUserMapper.selectById(userId);
        ByteArrayOutputStream byteArrayOutputStream = twoFaService.generateOptAuthPicByteArray(sysUser.getUserName());
        String base64Image = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
        model.addAttribute("codeImage", "data:image/png;base64," + base64Image);
        SysUser2fa sysUser2fa = sysUser2faService.getOneByUserId(userId);
        model.addAttribute("key", sysUser2fa.getSecretKey());
        model.addAttribute("userName", sysUser.getUserName());
        return "2fa_view";
    }
}
